package com.workingpub.commons.jdbc.builder.internal;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.workingpub.commons.jdbc.binding.WhereEntry;
import com.workingpub.commons.jdbc.builder.BuildContext;
import com.workingpub.commons.jdbc.builder.LogicResolver;
import com.workingpub.commons.jdbc.builder.ResolverFactory;

@Service
public class WhereResolver implements LogicResolver {
	private static final String LOCAL_PATTERN = "^and |or ";
	private static final String SQL_KEYWORD_Where = " Where";

	@Autowired
	private ResolverFactory resolverFactory;

	@Override
	public List<Object> getContext(BuildContext buildContext, Object logicEntry) {
		if (logicEntry instanceof WhereEntry) {
			WhereEntry whereEntry = (WhereEntry) logicEntry;
			List<Object> buildResults = resolverFactory.resolve(buildContext, whereEntry.getContent().toArray());
			if (!CollectionUtils.isEmpty(buildResults)) {
				List<Object> finalResults = new ArrayList<Object>();
				finalResults.add(SQL_KEYWORD_Where);
				boolean firstItem = true;
				for (Object obj : buildResults) {
					String item = String.valueOf(obj);
					if (StringUtils.isBlank(item)) {
						continue;
					}
					item = StringUtils.trim(item);
					if (firstItem) {
						Pattern localPattern = Pattern.compile(LOCAL_PATTERN, Pattern.CASE_INSENSITIVE);
						Matcher matcher = localPattern.matcher(item);
						if (matcher.find()) {
							item = matcher.replaceFirst(StringUtils.EMPTY);
						}
						firstItem = false;
					}
					finalResults.add(StringUtils.SPACE + item);
				}
				return finalResults;
			}
		}
		return null;
	}
}
